/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhanguera.tcc.model.converter;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 *
 * @author Diego
 */
public class BigDecimalFormatConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        if (value != null && !value.trim().equals("")) {
            value = value.replace(".", "");
            value = value.replace(",", "");
            BigDecimal num = null;
            try {
                num = new BigDecimal(value);
            } catch (NumberFormatException e) {

            }
            return num;
        } else {
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
        try {
            NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
            nf.setGroupingUsed(true);
            nf.setMaximumFractionDigits(2);
            nf.setMinimumFractionDigits(2);
            return nf.format(value);
        } catch (Exception e) {
            return null;
        }
    }

}
